<template>
<div>
  <div>
    <el-input style="width: 200px" placeholder="查询公告标题" v-model="titleSearch"></el-input>
    <el-input style="width: 200px; margin: 0 5px" placeholder="查询公告内容关键字" v-model="contentSearch"></el-input>
    <el-button type="primary" @click="load(1)">查询</el-button>
    <el-button type="primary" @click="reset">重置</el-button>
  </div>
  <div style="margin: 10px 0">
    <el-button type="primary" plain @click="handleAddOrEdit">新增</el-button>
    <el-button type="danger" plain @click="handleDelBatch">批量删除</el-button>
  </div>
<!--  整个表格，有多选框 -->
  <el-table v-loading="loading" element-loading-text="拼命加载中" :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color: '#666'}"
  @selection-change="handleSelectionChange">
<!--    复选框-->
    <el-table-column type="selection" width="55" align="center"></el-table-column>
    <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
    <el-table-column prop="title" label="标题"></el-table-column>
    <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
    <el-table-column prop="username" label="发布人" width="80"></el-table-column>
    <el-table-column prop="creatTime" label="创建时间" width="140"></el-table-column>
    <el-table-column prop="updateTime" label="修改时间" width="140"></el-table-column>
    <el-table-column prop="remark" label="是否公开">
      <template v-slot="scope">
        <el-switch v-model="scope.row.isOpen" @change="openChange(scope.row)"></el-switch>
      </template>
    </el-table-column>
    <el-table-column prop="remark" label="备注"></el-table-column>
    <el-table-column fixed="right" label="操作" align="center" width="180px">
      <template v-slot="scope">
        <el-button size="mini" type="primary" plain @click="handleAddOrEdit(scope.row)">编辑</el-button>
        <el-button size="mini" type="danger" plain @click="handleDel(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin: 10px 0;text-align: center">
    <el-pagination @current-change="handleCurrentChange"
                   :current-page="pageNum"
                   :page-size="pageSize"
                   layout="total,prev,pager,next"
                   :total="total">
    </el-pagination>
  </div>

  <!-- 新增表单需要弹窗包裹 / close-on-click-model点击弹窗外不会关闭-->
  <el-dialog title="公告信息"
             :visible.sync="formVisible"
             width="40%"
             :close-on-click-model="false">
    <el-form :model="form"
             label-width="80px"
             style="padding-right: 20px"
             :rules="rules"
             ref="formRef">

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="标题"></el-input>
      </el-form-item>

      <!-- prop 与rules字段绑定     -->
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" v-model="form.content" placeholder="内容"></el-input>
      </el-form-item>

<!--      <el-form-item label="作者" prop="author">-->
<!--        <el-input v-model="form.author" placeholder="作者"></el-input>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="创建时间" prop="datetime">-->
<!--        <el-input v-model="form.creatTime" placeholder="创建时间"></el-input>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="更新时间" prop="datetime">-->
<!--        <el-input v-model="form.updateTime" placeholder="更新时间"></el-input>-->
<!--      </el-form-item>-->

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="备注"></el-input>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="formVisible = false">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>

export default {
  name: "Notice",
  data(){
    return {
      tableData: []//表数据
      ,pageNum: 1//当前页码
      ,pageSize: 15//每页数量
      ,titleSearch: '' //搜索标题
      ,contentSearch: ''//搜索内容
      ,content: ''
      ,total: 0 //数据总条数
      ,formVisible: false //默认不显示新增表单弹窗
      ,form: {}
      ,user: JSON.parse(localStorage.getItem('userInfo') || '{}')
      ,rules: {
        title: [
          {required: true,message: '输入标题',trigger: 'blur'}
        ],
        content: [
          {required: true,message: '输入内容',trigger: 'blur'}
        ]
      }
      ,ids: []
      ,loading: true,
    }
  },
  created() {
    this.load();
  },
  methods: {
    reset(){
      this.titleSearch = ''
      this.contentSearch = ''
      this.load()
    },
    load(pageNum){
      if (pageNum) this.pageNum = pageNum;  //分页查询时自动切换到第一页
      this.$request.get('/notice/findByPage',{
        params:{
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.titleSearch,
          content: this.contentSearch
        }
      }).then(res => {
        if (res.data){
          if (res.data.records){
            // this.tableData = res.data
            this.tableData = res.data.records  //若records不显示可替换为List
          }else{
            this.$message.warning("res.data.records不存在")
          }
          this.total = res.data.total
        }else {
          this.$message.error("接口未返回数据，请重新登录")
        }
        this.loading = false
      })
    },
    //切换页码
    handleCurrentChange(pageNum){
      // this.pageNum = pageNum //方法传递过来参数就不用赋值了
      this.load(pageNum)
    },
    //新增弹窗事件||编辑弹窗
    //注意：row无论在哪种模式，永远不为空，只是值内容多少的区别，所以同函数无法精确区分两种模式，要么分函数，要么根据内容来区分
    handleAddOrEdit(row){
      // this.form = row.id ?  JSON.parse(JSON.stringify(row)) : {}
      //判断是否编辑模式，默认false
      if (row.id){
        this.isEditMode = true;
        this.form = JSON.parse(JSON.stringify(row)) //弹窗带出来信息,浅拷贝是内存指向，深拷贝是开区域赋值
      }else {
        this.isEditMode = false; //其实不用写，默认就是false
        this.form = {} //新增数据时清空表单
      }

      this.formVisible = true //显示弹窗
    },
    //发送save请求
    sendSave(){
      //发送请求
      this.$request({
        //有id就是编辑
        method: this.form.id ? 'PUT' : 'POST',
        data: this.form,
        url: this.form.id ? '/notice/update' : '/notice/save'
      }).then(res => {
        if (res.code === '200'){
          //保存成功
          this.$message.success('保存成功')
          this.formVisible = false;
          this.load(this.pageNum)
        }else {
          this.$message.error(res.msg) //错误信息
        }
      })
    },
    //新增保存
    save(){
      //校验表单
      this.$refs.formRef.validate((valid) => {
        if (valid){
          this.sendSave()
        }else {
          this.$message.warning("表单校验未通过")
        }
      })
    },
    //单个删除
    handleDel(row){
      this.$confirm('确认删除《'+row.title+'》公告吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/notice/delete/'+row.id).then(res => {
          if (res.code == '200'){
            this.$message.success("删除成功")
          }else {
            this.$message.error("删除失败："+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //批量删除之前--多选框，参数是选中的行对象
    handleSelectionChange(rows){
      this.ids = rows.map(row => row.id) //流和表达式，将行id提取出来存入数组
    },
    //批量删除
    handleDelBatch(){
      //校验：点击批量删除按钮之前，未选择多选框时提示
      if (!this.ids.length){
        this.$message.warning('请选择需要批量删除的公告！')
        return
      }

      this.$confirm('你确认批量删除['+this.ids+']这些公告吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/notice/deleteBatch',{data: this.ids}).then(res => {
          if (res.code == '200'){
            this.$message.success("批量删除成功")
          }else {
            this.$message.error("批量删除失败:"+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //是否公开 改变事件
    openChange(form){
      // this.form = form; //这样不合适，是属于直接指向内存地址，浅拷贝会直接改变影响数据库原本数据
      this.form = JSON.parse(JSON.stringify(form))  //变为与行对象没有关系，而是重新赋值，新建自己的内存空间，互不影响，属于深拷贝
      //调用更新，无需校验，直接发请求
      this.sendSave()
    }
  }
}
</script>

<style>
</style>